package com.cinyi.ormx.android.dao;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

import com.cinyi.ormx.android.context.LogHelper;
import com.cinyi.ormx.android.model.AndroidBaseModel;

public abstract class DefaultSQLiteHelper extends SQLiteOpenHelper {
	private static final String TAG = DefaultSQLiteHelper.class.getSimpleName();
	
	protected static byte lock[] = new byte[0];
	protected Context mContext;
	
	@SuppressWarnings("rawtypes")
	private List<AndroidBaseModel> tables;

	public DefaultSQLiteHelper(Context context, String name,
			CursorFactory factory, int version) {
		super(context, name, factory, version);
		this.mContext = context;
		tables = new ArrayList<AndroidBaseModel>();
	}

	@Override
	public void onOpen(SQLiteDatabase db) {
		super.onOpen(db);
	}

	@Override
	public void onCreate(SQLiteDatabase sqlitedatabase) {
		clearTables();
		initTables();
		for (AndroidBaseModel dt : tables) {
			dt.CreateIfNoExists(sqlitedatabase);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase sqlitedatabase, int oldVersion,
			int newversion) {
		clearTables();
		initTables();
		if (newversion > oldVersion) {
			for (AndroidBaseModel dt : tables) {
				dt.dropTableIfExists(sqlitedatabase);
			}
			onCreate(sqlitedatabase);
		} else {
			 LogHelper.d(TAG,"upgrade nothing.");
		}
		LogHelper.d(TAG,"upgrade from version ." + oldVersion + " to "+newversion);
	}

	public void addTable(AndroidBaseModel dt) {
		tables.add(dt);
	}

	public void clearTables() {
		tables.clear();
	}

	public static synchronized void closeCursor(Cursor cursor) {
		if (cursor != null) {
			cursor.close();
		}
	}
	
	public Context getContext() {
		return mContext;
	}

	public abstract void initTables();

	public abstract String getDatabaseName() ;
	
}
